package easier.amap;

import android.content.Context;
import androidx.annotation.Nullable;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationClientOption.AMapLocationProtocol;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.amap.api.maps.MapsInitializer;
import java.util.Calendar;
import java.util.Date;

/**
 * 高德定位工具,即开即用,用完即销毁{@link #startLocation(AMapLocationListener)}开始定位,{@link #destroyLocation()}销毁定位
 */
public class AMapEasier {

    private AMapLocationClient locationClient = null;

    public static void notifyUpdatePrivacyShow( Context context ) {

        MapsInitializer.updatePrivacyShow( context, true, true );
    }

    public static void notifyUpdatePrivacyAgree( Context context, boolean agree ) {

        MapsInitializer.updatePrivacyAgree( context, agree );
    }

    public static String print( AMapLocation location ) {

        if ( null != location ) {

            StringBuilder sb = new StringBuilder();
            //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
            if ( location.getErrorCode() == 0 ) {
                sb.append( "定位成功" + "\n" );
                sb.append( "定位类型: " ).append( location.getLocationType() ).append( "\n" );
                sb.append( "经    度    : " ).append( location.getLongitude() ).append( "\n" );
                sb.append( "纬    度    : " ).append( location.getLatitude() ).append( "\n" );
                sb.append( "精    度    : " ).append( location.getAccuracy() ).append( "米" ).append( "\n" );
                sb.append( "提供者    : " ).append( location.getProvider() ).append( "\n" );

                sb.append( "速    度    : " ).append( location.getSpeed() ).append( "米/秒" ).append( "\n" );
                sb.append( "角    度    : " ).append( location.getBearing() ).append( "\n" );
                // 获取当前提供定位服务的卫星个数
                sb.append( "星    数    : " ).append( location.getSatellites() ).append( "\n" );
                sb.append( "国    家    : " ).append( location.getCountry() ).append( "\n" );
                sb.append( "省            : " ).append( location.getProvince() ).append( "\n" );
                sb.append( "市            : " ).append( location.getCity() ).append( "\n" );
                sb.append( "城市编码 : " ).append( location.getCityCode() ).append( "\n" );
                sb.append( "区            : " ).append( location.getDistrict() ).append( "\n" );
                sb.append( "区域 码   : " ).append( location.getAdCode() ).append( "\n" );
                sb.append( "地    址    : " ).append( location.getAddress() ).append( "\n" );
                sb.append( "兴趣点    : " ).append( location.getPoiName() ).append( "\n" );
                //定位完成的时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime( new Date( location.getTime() ) );
                sb.append( "定位时间: " )
                    .append( calendar.get( Calendar.YEAR ) ).append( "-" )
                    .append( calendar.get( Calendar.MONTH ) + 1 ).append( "-" )
                    .append( calendar.get( Calendar.DAY_OF_MONTH ) ).append( " " )
                    .append( calendar.get( Calendar.HOUR_OF_DAY ) ).append( ":" )
                    .append( calendar.get( Calendar.MINUTE ) ).append( ":" )
                    .append( calendar.get( Calendar.SECOND ) )
                    .append( "\n" );
            } else {
                //定位失败
                sb.append( "定位失败" + "\n" );
                sb.append( "错误码:" ).append( location.getErrorCode() ).append( "\n" );
                sb.append( "错误信息:" ).append( location.getErrorInfo() ).append( "\n" );
                sb.append( "错误描述:" ).append( location.getLocationDetail() ).append( "\n" );
            }
            sb.append( "***定位质量报告***" ).append( "\n" );
            sb.append( "* WIFI开关：" ).append( location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭" )
                .append( "\n" );

            String str = "";
            switch ( location.getLocationQualityReport().getGPSStatus() ) {
                case AMapLocationQualityReport.GPS_STATUS_OK:
                    str = "GPS状态正常";
                    break;
                case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                    str = "手机中没有GPS Provider，无法进行GPS定位";
                    break;
                case AMapLocationQualityReport.GPS_STATUS_OFF:
                    str = "GPS关闭，建议开启GPS，提高定位质量";
                    break;
                case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                    str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                    break;
                case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                    str = "没有GPS定位权限，建议开启gps定位权限";
                    break;
            }

            sb.append( "* GPS状态：" ).append( str ).append( "\n" );
            sb.append( "* GPS星数：" ).append( location.getLocationQualityReport().getGPSSatellites() ).append( "\n" );
            sb.append( "* 网络类型：" ).append( location.getLocationQualityReport().getNetworkType() ).append( "\n" );
            sb.append( "* 网络耗时：" ).append( location.getLocationQualityReport().getNetUseTime() ).append( "\n" );
            sb.append( "****************" ).append( "\n" );

            //解析定位结果，
            return sb.toString();
        } else {
            return ("定位失败，loc is null");
        }
    }

    public AMapEasier( Context context ) {

        try {
            init( context );
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void init( Context context ) throws Exception {
        //初始化client
        locationClient = new AMapLocationClient( context.getApplicationContext() );
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {

        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode( AMapLocationMode.Hight_Accuracy );//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        option.setGpsFirst( false );//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        option.setHttpTimeOut( 30000 );//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        //mOption.setInterval( 2000 );//可选，设置定位间隔。默认为2秒
        option.setNeedAddress( true );//可选，设置是否返回逆地理地址信息。默认是true
        option.setOnceLocation( true );//可选，设置是否单次定位。默认是false
        option.setOnceLocationLatest( true );//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol( AMapLocationProtocol.HTTPS );//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        option.setSensorEnable( false );//可选，设置是否使用传感器。默认是false
        option.setWifiScan( true ); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        option.setLocationCacheEnable( true ); //可选，设置是否使用缓存定位，默认为true
        option.setGeoLanguage( AMapLocationClientOption.GeoLanguage.DEFAULT );//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return option;
    }

    /**
     * @param listener 开始定位,然后回调定位信息
     */
    public void startLocation( AMapLocationListener listener ) {

        startLocation( getDefaultOption(), listener );
    }

    /**
     * @param listener 开始定位,然后回调定位信息
     */
    public void startLocation( AMapLocationClientOption option, AMapLocationListener listener ) {

        try {
            // 设置监听
            locationClient.setLocationListener( listener );
            // 设置定位参数
            locationClient.setLocationOption( option );
            // 启动定位
            locationClient.startLocation();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    public void stopLocation() {

        try {
            // 停止定位
            locationClient.stopLocation();
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    public void destroyLocation() {

        if ( null != locationClient ) {
            stopLocation();
            /*
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    /**
     * @return 获取最后一次成功定位
     */
    @Nullable
    public AMapLocation getLastKnownLocation() {

        return locationClient.getLastKnownLocation();
    }
}
